'use strict';

const Service = require('egg').Service;

class IndexService extends Service {
  async index () {
    const shopId = 10002;
    const shop = await this.app.api.shops.get(shopId);
    const productIds = [];
    const slides = [];
    console.log(shop);
    if (shop.slides) {
      for (const slide of shop.slides) {
        if (slide && +slide.slideType === 1) {
          productIds.push(slide.id);
        }
      }
      if (productIds.length > 0) {
        let products = await this.app.api.products.getProductDetail(productIds);
        if (products) {
          if (productIds.length === 1) {
            slides.push({
              id: products.id,
              logo: products.logo
            });
          } else {
            for (const product of products) {
              slides.push({
                id: product.id,
                logo: product.logo
              });
            }
          }
        }
      }
    }
    const imgHost = this.app.config.qiniu.bucket.subImg.host;

    return {
      slides,
      imgHost
    };
  }

  async menu (shopId, tableId) {
    // 获取店铺信息

    // 获取桌位信息

    const shop = await this.app.api.shops.get(shopId);
    let cartTable = null;
    let productTypes = null;
    let products = null;
    if (tableId) {
      cartTable = await this.app.api.cartTables.get(tableId);
      if (cartTable && (+cartTable.shop.id !== +shopId || cartTable.status !== 0)) {
        cartTable = null;
      }
    }

    if (shop) {
      products = await this.app.api.products.getMenuProducts(shopId);
      if (products) {
        let productTypeIds = [];
        for (let product of products) {
          if (productTypeIds.indexOf(product.productType.id) === -1) {
            productTypeIds.push(product.productType.id);
          }
        }

        productTypes = await this.app.api.productTypes.getProductTypesByIdList(productTypeIds);
        if (productTypes && productTypeIds.length === 1) {
          productTypes = [productTypes];
        }
      }

      const imgHost = this.app.config.qiniu.bucket.subImg.host;
      return {
        shop,
        cartTable,
        products,
        productTypes,
        imgHost
      };
    } else {
      return {};
    }
  }
}
module.exports = IndexService;
